package link.anyauto.fsmgr.util;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import java.lang.reflect.Type;

import link.anyauto.fsmgr.FsmgrApp;

/**
 * Created by discotek on 16-7-18.
 */

public class StorageUtil {

    static SharedPreferences.Editor getEditor() {
        return getPref().edit();
    }

    static SharedPreferences getPref() {
        return PreferenceManager.getDefaultSharedPreferences(FsmgrApp.getInstance());
    }

    public static String get(String key) {
        return getPref().getString(key, null);
    }

    public static void save(String key, String str) {
        if(TextUtils.isEmpty(str)) {
            getEditor().remove(key).commit();
        } else {
            getEditor().putString(key, str).commit();
        }
    }

    public static void save(String key, Object obj) {
        if(obj != null) {
            save(key, GsonUtil.gson.toJson(obj));
        } else {
            save(key, null);
        }
    }

    public static <T> T get(String key, Class<T> clz) {
        String src = get(key);
        if(!TextUtils.isEmpty(src)) {
            return GsonUtil.gson.fromJson(src, clz);
        }
        return null;
    }

    public static <T> T get(String key, Type type) {
        String src = get(key);
        if(!TextUtils.isEmpty(src)) {
            return GsonUtil.gson.fromJson(src, type);
        }
        return null;
    }
}
